import { axios } from '@/utils/request'

// 文件下载
export const fileDownLoad = function (url, filename, params) {
  return axios({ url, params, method: 'get', responseType: 'blob' }).then(res => {
    if (res instanceof Blob) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(res, filename)
      } else {
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(res)
        link.download = filename
        link.style.display = 'none'
        // 兼容火狐浏览器
        document.body.appendChild(link)
        const evt = document.createEvent('MouseEvents')
        evt.initEvent('click', false, false)
        link.dispatchEvent(evt)
        document.body.removeChild(link)
      }
    }
    return Promise.resolve()
  })
}

// 文件导出
export const fileDownLoadFun = function (url, params) {
  return axios({ url, params, method: 'get', responseType: 'blob' })
}

// 文件导出
export const FileExport = function (url, params, method) {
  return axios({ url, data: params, method: method, responseType: 'blob' })
}

// 图片下载
export const imageDownLoad = function (url, params) {
  return new Promise((resolve, reject) => {
    axios({
      url,
      params,
      method: 'get',
      responseType: 'blob'
    })
      .then(res => {
        const reader = new FileReader()
        reader.onload = e => resolve(e.target.result)
        reader.onerror = e => reject(e)
        reader.readAsDataURL(res)
      })
      .catch(e => {
        reject(e)
      })
  })
}
